﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMS.Core.General;
using CMS.Core.Types;
using CMS.Core;
using CMS.Web.Filters;
using CMS.Web.Areas.Admin.Models;

namespace CMS.Web.Areas.Admin.Controllers
{
    public class RoleController : Controller
    {
        // GET: Admin/Role

        RoleManager roleManager = new RoleManager();

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 消息提示
        /// </summary>
        /// <returns></returns>
        public ViewResult Prompt(Prompt promtp)
        {
            return View(promtp);
        }

        /// <summary>
        /// 所有的角色数据
        /// </summary>
        /// <returns>角色数据集合Json</returns>
        public JsonResult ListJson()
        {
            var data = roleManager.FindList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns>返回Response类信息 </returns>
        [HttpPost]
        public JsonResult DeleteJson(int id = 0)
        {
            var response = roleManager.Delete(id);

            if(response.Code != 1)
            {
                response.Message = "删除失败";
            }

            return Json(response, JsonRequestBehavior.AllowGet); 
        }

       /// <summary>
       /// 添加角色
       /// </summary>
       /// <param name="role">要添加的角色信息</param>
       /// <returns>成功--重定向Prompt视图, 失败-返回错误信息</returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult AddRole(Role role)
        {
            Response response = new Response();
            if(ModelState.IsValid)
            {
                if(roleManager.HasRoleName(role.Name))
                {
                    response.Code = 0;
                    ViewBag.Message = "该角色名已经存在";
                    ModelState.AddModelError("Name","该角色名已经存在");
                }
                else
                {
                    roleManager.Add(role);
                    Prompt prompt = new Prompt()
                    {
                        Title = "添加角色成功",
                        Message = "阁下已成功添加角色 【" + role.Name + "】",
                        Buttons = new List<string>() { "<a href=\"" + Url.Action("Index", "Role") + "\" class=\"btn btn-default\">角色管理</a>", 
                            "<a href=\"" + Url.Action("AddRole", "Role") + "\" class=\"btn btn-success\">继续添加</a>" }
                    };
                    return View("_Prompt", prompt);
                }
            }

            return View(role);
        }
        public ViewResult AddRole()
        {
            return View();
        }


    }
}